import Component from "../Component.js";
import Type from "../../experience/db/Type.js";

const VectorSource = ol.source.Vector;
const Draw = ol.interaction.Draw;
const Modify = ol.interaction.Modify;

export default class Warning extends Component {
    constructor() {
        super();
    }

    async edit(self, select) {
        const modify = new Modify({ features: select.getFeatures() })
        modify.on('modifyend', (evt) => {
            evt.features.forEach(async (feature) => {
                const area = feature.getGeometry().flatCoordinates;
                self.coors = [];
                for (let i = 0; i < area.length - 1; i = i + 2) {
                    const x = self.algo.denormalX(area[i]);
                    const y = self.algo.denormalY(area[i + 1]);
                    self.coors.push([x, y])
                }
                const warnAreaCode = feature.getId();
                const config = self.algo.getConfig();
                const warning = {
                    mineCode: config.mine_code,
                    mineName: config.mine_name,
                    warnAreaCode: warnAreaCode,
                    geoType: 'POLYGON',
                    geoValue: self.utils.xys2str(this.coors)
                };
                const data = await self.api.updateWarning(warning);
                if (data.code === 0) {
                    const data = await this.api.getWarnAreaList(config.mine_code);
                    await this.db.refresh(Type.Warning, data.data);
                    await this.drawer.draw(Type.Warning);
                }
            })
        })

        self.drawer.addInteraction(modify);
    }

    async select(feature) {
        const self = this;
        const warningDateTime = feature.get("warningDateTime");
        const warningPosition = feature.get("warningPosition");
        const warningType = feature.get("warningType");
        const warningLevel = feature.get("warningLevel");
        const hazardReason = feature.get("hazardReason");
        const hazardSuggest = feature.get("hazardSuggest");
        const warningCancelTime = feature.get("warningCancelTime");

        self.$$("#warning-start-time").html(warningDateTime);
        self.$$("#warning-position").html(warningPosition);
        self.$$("#warning-type").html(warningType);
        self.$$("#warning-level").html(warningLevel);
        self.$$("#warning-reason").html(hazardReason);
        self.$$("#warning-suggest").html(hazardSuggest);
        self.$$("#warning-end-time").html(warningCancelTime);

        self.$$("#warning-popup-delete").show();
        self.$$("#warning-popup-modify").show();

        const geoType = feature.get('geoType');
        if (geoType === "POINT") {
            self.$$("#warning-popup-modify").hide();
        }

        self.$$("#warning-popup-delete").on("click", async () => {
            await self.deleteWarning(self, id);
            self.popup.close();
        });

        self.$$("#warning-popup-modify").on("click", async () => {
            await self.editWarning(self, select);
            self.popup.close();
        });

        self.popup.open();
    }

    async delete(id) {
        const data = await this.api.deleteWarning(id);
        const config = this.algo.getConfig();
        this.toast(data.msg);
        if (data.code === 0) {
            const data = await this.api.getWarnAreaList(config.mine_code);
            await this.db.refresh(Type.Warning, data.data);
            await this.drawer.draw(Type.Warning);
        }
    }

    async refresh() {
        const config = this.algo.getConfig();
        if (config == null) return

        const data = await this.api.getWarnAreaList(config.mine_code);
        if (data.data === null) {
            console.log("预警区域数据获取异常。", data);
            return;
        }

        await this.db.refresh(Type.Warning, data.data);
        await this.drawer.draw(Type.Warning);
    }

    point() {
        this.$$("#drawing-warning-point").on("click", () => {
            this.toast('请在地图上添加一个点。');
            const source = new VectorSource();
            const draw = new Draw({ source: source, type: 'Point' })
            draw.on('drawend', (event) => {
                this.drawer.locked = true

                const config = this.algo.getConfig();
                const point = event.feature.getGeometry().getCoordinates();
                const x = this.algo.denormalX(point[0]);
                const y = this.algo.denormalY(point[1]);
                this.app.dialog.prompt('请输入预警点名称.', async (name) => {
                    if (name === null || name === "") {
                        this.toast("预警区域名称不能为空。");
                        return;
                    }

                    const warn = {
                        geoType: 'POINT',
                        geoValue: this.utils.xys2str([[x, y]]),
                        mineCode: config.mine_code,
                        mineName: config.mine_name,
                        warnAreaName: name
                    };
                    const data = await this.api.insertWarning(warn);
                    this.toast(data.msg);
                    this.drawer.removeInteraction(draw);
                    await this.refresh();
                    this.drawer.locked = false
                },() => {
                    this.drawer.removeInteraction(draw);
                    this.drawer.locked = false
                });
            })
            this.drawer.addInteraction(draw);
        })
    }

    area() {
        this.$$("#drawing-warning-area").on("click", () => {
            this.toast('请描画一个图形面,双击结束。');
            const source = new VectorSource();
            const draw = new Draw({ source: source, type: 'Polygon' });
            draw.on('drawend', (event) => {
                this.drawer.locked = true

                const config = this.algo.getConfig();
                const area = event.feature.getGeometry().flatCoordinates, coors = [];
                for (let i = 0; i < area.length - 1; i = i + 2) {
                    const x = this.algo.denormalX(area[i]);
                    const y = this.algo.denormalY(area[i+1]);
                    coors.push([x, y]);
                }
                this.app.dialog.prompt('请输入预警区域名称.', async (name) => {
                    if (name === null || name === "") {
                        this.toast("预警区域名称不能为空。");
                        return;
                    }

                    const warn = {
                        geoType: 'POLYGON',
                        geoValue: this.utils.xys2str(coors),
                        mineCode: config.mine_code,
                        mineName: config.mine_name,
                        warnAreaName: name
                    }
                    const data = await this.api.insertWarning(warn);
                    this.toast(data.msg)
                    this.drawer.removeInteraction(draw);
                    await this.refresh();
                    this.drawer.locked = false
                },() => {
                    this.drawer.removeInteraction(draw);
                    this.drawer.locked = false
                });
            })

            this.drawer.addInteraction(draw);
        })
    }

    template() { }

    control() {
        this.point();
        this.area();
    }
}